//请求公共方法
/**
 * 登陆逻辑参考 backup 内的doc
 */
import promise from './promise.js'
const {
  code: CODE,
  server: SERVER,
  tip: TIP
} = require("./config.js");
// const {api} = require("interface.js");
import toast from "./toast.js";


let newPromise = promise.uniPromise(uni.request);
let app = getApp();
let userInfo = app.globalData.userInfo || {};

let params = (method="POST") => {
  let token = uni.getStorageSync('TOKEN')
  return {
    header: {
      'X-Requested-With': 'XMLHttpRequest',
      'token': token
    },
    method: method,
  }
}
/**
 * http请求的公共方法
 * @param {string} url-接口地址
 * @param {string} method-请求方式,传入的话，默认post请求
 * @param {Object} data - 请求参数
 */
const request = ({url,method = "POST",data = {}}) => {
  uni.showNavigationBarLoading();
    return newPromise(Object.assign({
        url: SERVER + url,
        data: data
    }, params(method)))
      .then(res => {
		  console.log(res)
        if (res.data.code == "51008") {
          toast.tip(res.data.message)
          //未登录重新登陆
          return relogin(url, data, method).then(res=>{
            return Promise.resolve(res.data)
          })
        } else if (res.data.code == "51009"){
          //登录超时重新登陆
          return relogin(url, data, method).then(res => {
            return  Promise.resolve(res.data)
          })
        } else if (res.data.code == "60001"){
          toast.tip(res.message);
        } else if(res.data.success){ // 测试，接入正式接口请移除该条件
			uni.hideNavigationBarLoading();
			return Promise.resolve(res.data.data)
		} else {
          //请求数据返回成功
          // console.log(res)
          if (res.data.code == CODE.SUCCESS) { //状态码200
            uni.hideNavigationBarLoading();
            return  Promise.resolve(res.data)
          } else if (res.data.code == CODE.EXCEPTION) {  //状态码500
            toast.tip(res.data.message);
            return Promise.reject(res.data)
          } else {
            //如果所有证件已预定环保车门票，则不提示信息
            if (res.data.code !== "52028"){
              toast.tip(res.data.message);
            }
            return Promise.reject(res.data)
          }
        }
      })
      .catch(error => {
        console.log('------打印请求抛出错误信息--------')
        console.log(error)
        uni.hideNavigationBarLoading();
        toast.hideLoading();
        //如果所有证件已预定环保车门票，则不提示信息
        if (error.code !== "52028") {
          toast.tip(error.message || TIP.network);
        }
        return Promise.reject(error);
      })
}
/**
 * 用户登陆
 */
const relogin = (url, data = {}, method = "POST") => {
  return promise.uniPromise(uni.login)()
    .then(res => {
      let code = res.code;
      return newPromise({
          url: SERVER + api.wechatUserAction + "?js_code=" + code + "&appId=" + app.globalData.appid,
          data: app.globalData.userInfo,
          header: {
            'X-Requested-With': 'XMLHttpRequest',
          },
        method: method,
        })
        .then(res => {
          uni.setStorageSync('TOKEN', res.data.data); 
          uni.hideNavigationBarLoading();
          return newPromise(Object.assign({
            url: SERVER + url,
            data: data
          }, params(method)))
        })
    }).catch(err => {
      console.log(err)
      toast.tip(err)
    })
}
/**
 * 用户授权
 * @params{boolean} --isAuth是否授权 true 已授权 / false 未授权
 */
// const getAuth = function(isAuth) {
//   if (isAuth)
//     return Promise.resolve();
//   else {
//     let getSetting = promise.uniPromise(uni.getSetting);
//     let getUserInfo = promise.uniPromise(uni.getUserInfo);
//     //获取appid
//     const accountInfo = uni.getAccountInfoSync();
//     app.globalData.appid = accountInfo.miniProgram.appId;
//     return getSetting().then(res => {
//       if (res.authSetting["scope.userInfo"]) {
//         app.globalData.isAuth = true;
//         return getUserInfo({
//           withCredentials: true
//         })
//       } else {
//         let url = getCurrentPage();
//         uni.redirectTo({
//           url: url + "pages/auth/index",
//         })
//       }
//     }).then(res => {
//       app.globalData.userInfo = res;
//       return Promise.resolve();
//     }).catch(error=>{console.error(error)})
//   }
// }
/**
 * 获取页面路径
 */
const getCurrentPage = () => {
  const length = getCurrentPages().length;
  const currentRoute = getCurrentPages()[length - 1].route;
  const pathIndex = currentRoute.split('/').length;
  let url = ""
  for (let i = 0; i < pathIndex - 1; i++) {
    url += '../'
  } 
  return url
}

export default {
  request: request,
  relogin: relogin
}